package br.com.onlinebidding.dao;



import java.util.List;

import org.hibernate.Session;

import br.com.onlinebidding.config.HibernateUtil;
import br.com.onlinebidding.entity.Product;

public class ProductDao {
	
  public Product getProduct (int id){
		
		Session sessao = null;
		sessao = HibernateUtil.getSessionFactory().openSession();
		
		return (Product) sessao.load(Product.class, id);
	}
	
	public static boolean insert(Product p){
		Session sessao = null;
		
		try{
			sessao = HibernateUtil.getSessionFactory().openSession();
			sessao.beginTransaction();
			sessao.save(p);
			sessao.getTransaction().commit();
			sessao.close();
			return true;
			
		}catch (Exception e){
			
			System.out.print("Erro ProductDao.insert():"+e.getMessage());
		}finally{
			if(sessao.isConnected()){
				sessao.close();
			}
		}
		return false;
		
	}
	
	public static List<Product> getAll() {
		String comando = "from Product";
		List<Product> lista = null;
		Session sessao = null;

		try {
			sessao = HibernateUtil.getSessionFactory().openSession();
			lista = (List<Product>) sessao.createQuery(comando).list();
		} catch (Exception ex) {
			System.out.println("Erro ProductDao.getAll(): " + ex.getMessage());
		} finally {
			if (sessao.isConnected()) {
				sessao.close();
			}
		}
		return lista;
	}
	
	public static Product getByIdRetObjeto(Integer id) {

		Session sessao = null;
		Product p = null;
		try {
			sessao = HibernateUtil.getSessionFactory().openSession();
			p = (Product) sessao.get(Product.class, id);

		} catch (Exception ex) {
			System.out.println("Erro ProductDao.getByIdRetObjeto():"
					+ ex.getMessage());
		} finally {
			if (sessao.isConnected()) {
				sessao.close();
			}
		}
		return p;
	}
	
	public static boolean update(Product p) {
		Session sessao = null;

		try {
			sessao = HibernateUtil.getSessionFactory().openSession();
			sessao.beginTransaction();
			sessao.update(p);
			sessao.getTransaction().commit();
			sessao.close();
			return true;

		} catch (Exception ex) {
			System.out.println("Erro ProductDao.update();" + ex.getMessage());

		} finally {
			if (sessao.isConnected()) {
				sessao.close();
			}
		}
		return false;
	}

	public static boolean delete(Product p) {
		Session sessao = null;

		try {
			sessao = HibernateUtil.getSessionFactory().openSession();
			sessao.beginTransaction();
			sessao.delete(p);
			sessao.getTransaction().commit();
			sessao.close();
			return true;

		} catch (Exception ex) {
			System.out.println("Erro ProductDao.delete();" + ex.getMessage());

		} finally {
			if (sessao.isConnected()) {
				sessao.close();
			}
		}
		return false;
	}

	
	
}//fim ProductDao
